import {Ref, isReactive, ReactiveEffectOptions, isRef} from 'vue'

interface LoadingConfig {
    ref: any;
    loadingName?: string;
}

function setLoading(obj: LoadingConfig, val) {
    const {ref,loadingName} = obj
    if (ref == undefined) return

    if (isRef(ref)) {
        ref.value = val
    } else if (isReactive(ref)){
        loadingName && (ref[loadingName] = val)
    }
}

export const useAsync = async (func: Promise<any>, loading: LoadingConfig): Promise<any> => {

    setLoading(loading, true)

    const data = await func.finally(() => setLoading(loading, false))

    return data
}

